package com.summer_administration.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.summer_administration.exception.BusinessException;
import com.summer_administration.mapper.MaterialMapper;
import com.summer_administration.pojo.Material;
import com.summer_administration.pojo.PageBean;
import com.summer_administration.service.MaterialService;
import com.summer_administration.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Map;

@Service
public class MaterialServiceImpl implements MaterialService {
    @Autowired
    private MaterialMapper materialMapper;

    @Override
    @Transactional
    public void add(Material material) {
        // 验证物资名称唯一性
        if (materialMapper.existsByName(material.getMetName())) {
            throw new BusinessException("物资名称已存在");
        }

        // 设置创建信息
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        material.setCreateUser((Integer) userInfo.get("id"));
        material.setCreateTime(LocalDateTime.now());
        material.setUpdateTime(LocalDateTime.now());

        materialMapper.add(material);
    }

    @Override
    public PageBean<Material> list(Integer pageNum, Integer pageSize) {
        PageBean<Material> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);

        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Integer userId = (Integer) userInfo.get("id");
        Page<Material> page = (Page<Material>) materialMapper.listByUser(userId);

        //pb.setTotal(page.getTotal());
        pb.setItems(page.getResult());
        return pb;
    }

    @Override
    @Transactional
    public void update(Material material) {
        Material existing = materialMapper.getById(material.getId());
        if (existing == null) {
            throw new BusinessException("物资不存在");
        }

        // 验证名称冲突
//        if (!existing.getMetName().equals(material.getMetName())
//                && materialMapper.existsByName(material.getMetName())) {
//            throw new BusinessException("物资名称已存在");
//        }

        // 保留创建信息
        material.setCreateUser(existing.getCreateUser());
        material.setCreateTime(existing.getCreateTime());
        material.setUpdateTime(LocalDateTime.now());

        materialMapper.update(material);
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        if (materialMapper.getById(id) == null) {
            throw new BusinessException("物资不存在");
        }
        materialMapper.delete(id);
    }
}
